package org.jeecg.modules.xindian.reconciliation.controller;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.xindian.reconciliation.controller.req.IdWapper;
import org.jeecg.modules.xindian.reconciliation.controller.req.ReportManagerReq;
import org.jeecg.modules.xindian.reconciliation.controller.req.SettlementOne;
import org.jeecg.modules.xindian.reconciliation.controller.rsp.BrokerageFeeSettlementInfoExcel;
import org.jeecg.modules.xindian.reconciliation.controller.rsp.CommonDataStatic;
import org.jeecg.modules.xindian.reconciliation.controller.rsp.MangeOptions;
import org.jeecg.modules.xindian.reconciliation.controller.rsp.SettlementPolicyInfoExcel;
import org.jeecg.modules.xindian.reconciliation.dto.rsp.SalesmanManagerInfo;
import org.jeecg.modules.xindian.reconciliation.entity.ChannelSettlementConfig;
import org.jeecg.modules.xindian.reconciliation.entity.PolicySettlementStatistics;
import org.jeecg.modules.xindian.reconciliation.entity.PolicyUnSettlementTypeStatistics;
import org.jeecg.modules.xindian.reconciliation.entity.Salesman;
import org.jeecg.modules.xindian.reconciliation.mapper.PolicySettlementStatisticsMapper;
import org.jeecg.modules.xindian.reconciliation.service.*;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.jeecg.modules.xindian.reconciliation.controller.req.ReportManagerReq.Type.SALESMAN;

@Api(tags = "保险公司结算模块")
@RestController
@RequestMapping("/settlementMange")
@Slf4j
public class SettlementMangeController {
    @Autowired
    private PolicySettlementStatisticsMapper settlementInfoMapper;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IPolicySettlementStatisticsService policySettlementStatisticsService;
    @Autowired
    private IPolicyUnSettlementTypeStatisticsService policyUnSettlementTypeStatisticsService;
    @Autowired
    private ISalesmanService salesmanService;
    @Autowired
    private IChannelSettlementConfigService channelSettlementConfigService;
    /**
     * 账单周期记录
     *
     * @return
//     */
    //@AutoLog(value = "杭州银行资金流水-分页列表查询")
    @ApiOperation(value = "账单周期记录", notes = "账单周期记录")
    @GetMapping(value = "info")
    public Result<IPage<SalesmanManagerInfo>> info( ReportManagerReq req) {
        log.info("账单周期请求参数如下:{}", req);
        Assert.notNull(req.getPageSize(), "页数不能为空");
        Assert.isTrue(StringUtils.hasText(req.getDate())||StringUtils.hasText(req.getPayDate()), "账单周期或者支付周期不能为空");
        Assert.notNull(req.getType(), "类型不能为空");
        Assert.notNull(req.getPageIndex(), "页码不能为空");
        Page<SalesmanManagerInfo> page = new Page<>(req.getPageIndex(), req.getPageSize());
        IPage<SalesmanManagerInfo> pageInfo = null;
        ReportManagerReq.Type type = ReportManagerReq.Type.valueOf(req.getType());
        switch (type){
            case INSURANCE: {
                pageInfo  =   settlementInfoMapper.queryInsuranceInfo(page, req.getDate(),req.getPayDate());
            }break;
            case CHANNEL: {
                pageInfo  =   settlementInfoMapper.queryChannelInfo(page, req.getDate(),req.getPayDate());
            }break;
            case SALESMAN: {
                pageInfo  =   settlementInfoMapper.querySalemanInfo(page, req.getDate(),req.getPayDate());
            }break;
        }
        return Result.ok(pageInfo);
    }



    /**
     * 保单明细
     * @param idWapper
     */
    //@RequiresPermissions("banck:insurance_hangzhou_back:exportXls")@\
    @ApiOperation(value = "保单明细导出", notes = "保单明细导出")
    @GetMapping(value = "exportXlsPolicyInfo")
    public ModelAndView exportXlsPolicyInfo(ReportManagerReq req, HttpServletRequest request) {
        Assert.notNull(req.getType(), "类型不能为空");
        Assert.notNull(req.getName(), "类型名称不能为空");
        Assert.notNull(req.getDate(), "周期不能为空");
        List<SettlementPolicyInfoExcel> policyInfoExcels = settlementInfoMapper.querySettlementPolicyInfo(req);
        //处理数据
        if(req.getType().equals("CHANNEL")){
            //处理渠道数据
            policyInfoExcels.forEach(ct->{
                if(req.getName().equals(ct.getChannelName())){
                    ct.setBrokerageFee(ct.getChannelFee());
                    ct.setBrokerageFeeRate(ct.getChannelFeeRate());
                }else {
                    ct.setBrokerageFee(ct.getChannelAloneFee());
                    ct.setBrokerageFeeRate(ct.getChannelAloneRate());
                }
            });
        }
        return this.exportXls(request, policyInfoExcels, SettlementPolicyInfoExcel.class, "保单明细");
    }


    /**
     * 经纪费明细
     *
     * @param idWapper
     */
    //@RequiresPermissions("banck:insurance_hangzhou_back:exportXls")@\
    @ApiOperation(value = "经纪费明细", notes = "经纪费明细")
    @GetMapping(value = "exportXlsBrokerageFeeInfo")
    public ModelAndView exportXlsBrokerageFeeInfo(IdWapper idWapper, HttpServletRequest request) {
        Assert.notNull(idWapper.getId(), "数据主键不能为空");
        List<BrokerageFeeSettlementInfoExcel> policyInfoExcels = settlementInfoMapper.queryInsuranceFreeBySettlementId(idWapper.getId());
        return this.exportXls(request, policyInfoExcels, BrokerageFeeSettlementInfoExcel.class, "经纪费明细");
    }


    /**
     * 导出excel
     *
     * @param request
     */
    protected <T> ModelAndView exportXls(HttpServletRequest request, List<T> exportList, Class<T> clazz, String title) {
        // Step.1 组装查询条件
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, clazz);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setType(ExcelType.HSSF);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 分页列表查询
     *
     * @param policySettlementStatistics
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "policy_settlement_statistics-分页列表查询")
    @ApiOperation(value="policy_settlement_statistics-分页列表查询", notes="policy_settlement_statistics-分页列表查询")
    @GetMapping(value = "settlementList")
    public Result<IPage<PolicySettlementStatistics>> settlementList(PolicySettlementStatistics policySettlementStatistics,
                                                                                                         @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                                                         @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                                                         HttpServletRequest req) {
        QueryWrapper<PolicySettlementStatistics> queryWrapper = QueryGenerator.initQueryWrapper(policySettlementStatistics, req.getParameterMap());
        Page<PolicySettlementStatistics> page = new Page<PolicySettlementStatistics>(pageNo, pageSize);
        IPage<PolicySettlementStatistics> pageList = policySettlementStatisticsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 经纪费明细
     * @param
     */
    //@RequiresPermissions("banck:insurance_hangzhou_back:exportXls")@\
    @ApiOperation(value = "已结算明细导出", notes = "已结算明细导出")
    @GetMapping(value = "exportXlSettlementList")
    public ModelAndView exportXlSettlementList(PolicySettlementStatistics policySettlementStatistics,
                                               HttpServletRequest req) {
        QueryWrapper<PolicySettlementStatistics> queryWrapper = QueryGenerator.initQueryWrapper(policySettlementStatistics, req.getParameterMap());
        List<PolicySettlementStatistics> pageList = policySettlementStatisticsService.list(queryWrapper);
        return this.exportXls(req, pageList, PolicySettlementStatistics.class, "已结算明细");
    }

    /**
     * 分页列表查询
     *
     * @param policyUnSettlementTypeStatistics
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "未结算明细-分页列表查询")
    @ApiOperation(value="未结算明细-分页列表查询", notes="未结算明细-分页列表查询")
    @GetMapping(value = "unSettlementList")
    public Result<IPage<PolicyUnSettlementTypeStatistics>> unSettlementList(PolicyUnSettlementTypeStatistics policyUnSettlementTypeStatistics,
                                                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                            HttpServletRequest req) {
        QueryWrapper<PolicyUnSettlementTypeStatistics> queryWrapper = QueryGenerator.initQueryWrapper(policyUnSettlementTypeStatistics, req.getParameterMap());
        Page<PolicyUnSettlementTypeStatistics> page = new Page<PolicyUnSettlementTypeStatistics>(pageNo, pageSize);
        IPage<PolicyUnSettlementTypeStatistics> pageList = policyUnSettlementTypeStatisticsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 经纪费明细
     * @param
     */
    //@RequiresPermissions("banck:insurance_hangzhou_back:exportXls")@\
    @ApiOperation(value = "未结算明细导出", notes = "已结算明细导出")
    @GetMapping(value = "exportXlUnSettlementList")
    public ModelAndView exportXlUnSettlementList(PolicyUnSettlementTypeStatistics unSettlementTypeStatistics,
                                               HttpServletRequest req) {
        QueryWrapper<PolicyUnSettlementTypeStatistics> queryWrapper = QueryGenerator.initQueryWrapper(unSettlementTypeStatistics, req.getParameterMap());
        List<PolicyUnSettlementTypeStatistics> pageList = policyUnSettlementTypeStatisticsService.list(queryWrapper);
        return this.exportXls(req, pageList, PolicyUnSettlementTypeStatistics.class, "未结算明细");
    }



    /**
     * 分页列表查
     * @return
     */
    //@AutoLog(value = "未结算明细-分页列表查询")
    @ApiOperation(value="未结算明细-分页列表查询", notes="未结算明细-分页列表查询")
    @GetMapping(value = "getMangeOptions")
    public Result<List<MangeOptions>> getMangeOptions(@RequestParam(name="type") String  type) {
        if(type.equals(SALESMAN.name())){
            return Result.OK(salesmanService.selectOption());
        }else {
            List<ChannelSettlementConfig> configs = channelSettlementConfigService.queryEnableConfig();
           return Result.OK(configs.stream().map(one->{
                MangeOptions  options = new MangeOptions();
                options.setId(one.getId());
                options.setTag(one.getChannel());
                return options;
            }).collect(Collectors.toList()));
        }
    }



    /**
     * 分页列表查询
     * @return
     */
    //@AutoLog(value = "未结算明细-分页列表查询")
    @ApiOperation(value="未结算明细-分页列表查询", notes="未结算明细-分页列表查询")
    @PostMapping(value = "settlementOne")
    public Result<?> settlementOne(@RequestBody  SettlementOne one) {
        Assert.notBlank(one.getType(),"请选择类型");
        if(one.getType().equals(SALESMAN.name())){
            Assert.notBlank(one.getSalesmanId(),"请选择业务员");
            Assert.notNull(one.getSalesmanRate(),"请填写业务员费率");
        }else {
            Assert.notBlank(one.getChannelId(),"请选择渠道");
        }
        policySettlementStatisticsService.settlementOne(one);
        return Result.OK();
    }
}
